<?php
defined('_JEXEC') or die;

jimport('joomla.database.table');

function sendHttpStatus($code, $text)
{
	header("HTTP/1.0 ".$code." ".$text);
	exit;
}

/*
 * @todo Joomla-Controller-Logik nutzen
 * @todo Test-Daten rausnehmen
 */
function dispatcher()
{
	/*
	 * Kommt die Google-Secret-Info mit?
	 */
	$strGoogleSecretInfo = ''; 
	$strGoogleCodeServerKey = 'HTTP_GOOGLE_CODE_PROJECT_HOSTING_HOOK_HMAC';
	if(array_key_exists($strGoogleCodeServerKey, $_SERVER))
	{
		$strGoogleSecretInfo = $_SERVER[$strGoogleCodeServerKey];
	}
	if('' == $strGoogleSecretInfo)
	{
		sendHttpStatus(403, 'Forbidden');
	}
	
	/*
	 * Daten aus dem Request-Body holen
	 */
	$strRevisionData = file_get_contents('php://input');
	if(false === $strRevisionData)
	{
		// Dem Client nicht (!) sagen dass Daten fehlen ... Der muss nicht wissen was wir für Daten erwarten
		sendHttpStatus(403, 'Forbidden');
	}
	
	/*
	 * JSON 2 PHP
	 */ 
	$result = json_decode($strRevisionData);
	if(null === $result)
	{
		sendHttpStatus(403, 'Forbidden');
	}
	
	/*
	 * Datenbankzugriff vorbereiten
	 */ 
	$db = JFactory::getDBO();
	
	/*
	 * Den Google-Secret-Key des Projektes holen
	 */ 
	$strProjectname = $result->project_name;
	$query = $db->getQuery(true);
	$query->from('#__UrksPCW_projects');
	$query->select('*');
	$query->where('project_name = '.$db->quote($strProjectname));
	$db->setQuery((string)$query);
	$projects = $db->loadObjectList();
	
	if(1 != count($projects))
	{
		// Projekt nicht oder mehrmals gefunden ...
		sendHttpStatus(403, 'Forbidden');
	}
	
	$dbProject = array_pop($projects);
	
	$strHashKey = hash_hmac('md5', $strRevisionData, $dbProject->secret_key); 
	
	if($strHashKey !== $strGoogleSecretInfo)
	{
		// Hackversuch? ...
		sendHttpStatus(403, 'Forbidden');
	}
	
	foreach($result->revisions as $revision)
	{
		$data = new stdClass();
		$data->id = null;
		$data->project_name = $result->project_name;
		$data->repository_path = $result->repository_path;
		
		$data->revision = $revision->revision;
		$data->url = $revision->url;
		$data->author = $revision->author;
		$data->datetime = date('Y-m-d H:i:s', $revision->timestamp);
		$data->message = $revision->message;
		$data->path_count = $revision->path_count;
		$data->added_phpsa = serialize($revision->added);
		$data->modified_phpsa = serialize($revision->modified);
		$data->removed_phpsa = serialize($revision->removed);
		
		$db->insertObject('#__UrksPCW_revisions', $data, 'id');
	}
	

	sendHttpStatus('200', 'Success');
}

dispatcher();